/*
	* jQuery Templatizer ~ 
	* :: Quick and easy templating for jQuery
	* Code: http://jquery-templatizer.googlecode.com/
	* Examples: http://www.snaptortoise.com/plugins/jquery-templatizer
	* Copyright (c) 2009 George Mandis (georgemandis.com, snaptortoise.com)
	* Version: 1.0 (5/06/2010)
	* Licensed under the GNU General Public License v3
	* http://www.gnu.org/copyleft/gpl.html
	* Tested in: Safari 4+, Google Chrome 4+, Firefox 3+, IE7+ and Mobile Safari 2.2.1
*/


	jQuery.templatizer ={
		load: function(url,name) {
		// Load the template

			name = name ? name : 0
			this.tpl[name] = $("<div></div>").load(url,function(responce){															
				jQuery.templatizer.ready=true;
				jQuery.templatizer.run_queue(name);
			});
		},
		tpl:[],
		ready:false,
		queue:[],
		run_queue:function(tpl){

			for (i in jQuery.templatizer.queue) {

				destination = jQuery.templatizer.queue[i].destination
				vars = jQuery.templatizer.queue[i].vars;
				tpl_name = jQuery.templatizer.queue[i].tpl_name
				append =  jQuery.templatizer.queue[i].append
					if (tpl_name==tpl) {
						jQuery(destination).templatizer(
							{
								data:vars,
								template:tpl_name,
								append:append
							});
						jQuery.templatizer.queue.splice(i,1);
						}
			}
		}
	}
	
jQuery.fn.templatizer = function(settings) {
	// use the template
	/*
		Settings:
		
		{
			template: "", // Name of template you want to use
			append: true, // Can either append to element or replace contents
			data: { 
				// Mapped data for template goes here  
				},
			
		}
	*/

	if (!jQuery.templatizer.ready) {
		// add to queue
		tpl_name = settings.template ? settings.template : 0;

		jQuery.templatizer.queue[jQuery.templatizer.queue.length] = {
			destination:this,
			vars:settings.data,
			tpl_name:settings.template,
			append:settings.append}
		return false
	}

		var new_tpl = jQuery.templatizer.tpl[settings.template].clone();
		// Fill elements
		new_tpl.each(function(i,val){
			// Take the current content
				currentHtml = $(this).html();

				// Cycle through variables to set; replace any matched vars
				if (currentHtml.indexOf("$") > 0) {
				for (n in settings.data) {
					var find  = new RegExp('\\$'+n, 'gi');
					currentHtml = currentHtml.replace(find, settings.data[n]);
					}
				}

				// Update the element
				$(this).html(currentHtml);					
				});
			
			

  // this.each(function() {

    	if (settings.append != true) {
				$(this).html(new_tpl) // Replace
			}else{ 
				$(this).append(new_tpl)	// Append
			}
  //});
  return this;

};

